package com.savitar.dict.service;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.savitar.common.annotation.Create;
import com.savitar.common.annotation.Update;
import com.savitar.common.entity.BaseModel;
import com.savitar.dict.dao.DictTypeMapper;
import com.savitar.dict.entity.DictType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * (DictType)表服务接口
 *
 * @author Savitar
 * @since 2021-05-19 21:07:32
 */
@Service
public class DictTypeService extends ServiceImpl<DictTypeMapper, DictType> {

    public Page<DictType> page(Integer pageNum, Integer pageSize, String key) {
        Page<DictType> page = new Page<>(pageNum,pageSize);
        return lambdaQuery().eq(StringUtils.isNotBlank(key), DictType::getDictType, key).or()
                .eq(StringUtils.isNotBlank(key), DictType::getNoteDesc, key).page(page);
    }

    @Create
    public DictType create(DictType createVo) throws Exception {
        Integer count = lambdaQuery().eq(DictType::getDictType, createVo.getDictType()).count();
        if(count > 0) {
            throw new Exception("字典类型重复");
        }
        createVo.setPkId(IdUtil.simpleUUID());
        createVo.insert();
        return createVo;
    }

    @Update
    public DictType update(DictType updateVo) throws Exception {
        DictType dictType = lambdaQuery().eq(DictType::getDictType, updateVo.getDictType()).one();
        if(dictType != null && !dictType.getPkId().equals(updateVo.getPkId())) {
            throw new Exception("字典类型重复");
        }
        updateVo.updateById();
        return updateVo;
    }

    public DictType deleteById(String id) {
        DictType one = lambdaQuery().eq(DictType::getPkId, id).one();
        one.deleteById();
        return one;
    }
}